
#include "stm32f10x.h"
#include "hw_config.h"
#include "stm32f10x_adc.h"
#include "stm32f10x_rcc.h"

void adc_hw_init() {
    ADC_InitTypeDef ADC_InitStructure;
    
    RCC_APB2PeriphClockCmd(RCC_APB2ENR_ADC1EN, ENABLE);
    
    /******************** ADC1 - voltage ******************************************/

    ADC_StructInit(&ADC_InitStructure);
    //select independent conversion mode (single)
    ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
    //We will convert single channel only
    ADC_InitStructure.ADC_ScanConvMode = DISABLE;
    //we will convert one time
    ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
    //select no external triggering
    ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
    //right 12-bit data alignment in ADC data register
    ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
    //single channel conversion
    ADC_InitStructure.ADC_NbrOfChannel = 1;
    //load structure values to control and status registers
    ADC_Init(ADC1, &ADC_InitStructure);
    //wake up temperature sensor
    ADC_TempSensorVrefintCmd(ENABLE);
    //ADC1 channel16 configuration
    //we select 41.5 cycles conversion for channel16
    //and rank=1 which doesn't matter in single mode
    ADC_RegularChannelConfig(ADC1, ADC_Channel_16, 1, ADC_SampleTime_41Cycles5);

    ADC_Cmd(ADC1, ENABLE);
    //Enable ADC1 reset calibration register
    ADC_ResetCalibration(ADC1);
    //Check the end of ADC1 reset calibration register
    while(ADC_GetResetCalibrationStatus(ADC1));
    //Start ADC1 calibration
    ADC_StartCalibration(ADC1);
    //Check the end of ADC1 calibration
    while(ADC_GetCalibrationStatus(ADC1));

}


uint8_t read_adc() {
    return 0;
}
